#include <GL/glut.h>
#include <unistd.h>
#include <math.h>
#include <iostream>
#include <assert.h>
#include "globals_.h"

using namespace std;

inline float sec_to_ms(float number){
	return (number/1000.0);
}

inline float round2(float val){//2 decimals
	return floor(val * 100 +  0.5) / 100;
}

bool going_up = false;

float max_h = h;

void Animation(int unused){

	++_time;
	Yi = h + ( Vi * sec_to_ms(_time) ) + ( g * pow(sec_to_ms(_time),2.0) ) / 2.0;

	float V = Vi + (g*sec_to_ms(_time));

	if( Yi <= 0  && !going_up){
		float Vf = sqrt(2.0*abs(g)*max_h);
		Vi = restitution*Vf;
		if(round2(Vi)==0) return;
		h = 0.0;
		Yi = 0.0;
		_time = 0;
		max_h = pow(Vi,2)/(2.0*abs(g));
		going_up = true;
	}
	else if(round2(V) == 0){
		going_up = false;
	}

	glutPostRedisplay();
	glutTimerFunc(TIME,Animation,1);
}

void Mostrar(){
	glClearColor(1,1,1,1);
	glClear(GL_COLOR_BUFFER_BIT);
	glLoadIdentity();

	gluOrtho2D(0,WIDTH,0-(round((float)SIZE_POINT)/100.0),HEIGHT+(round((float)SIZE_POINT)/100.0));

	glPointSize(SIZE_POINT);

	glColor3f(0,0,0);
	glBegin(GL_POINTS);
		glVertex2f(Xi, Yi);
	glEnd();

	glFlush();
}

int main(int argc, char** argv) {
	glutInit(&argc, argv);

	glutInitWindowSize(WINDOW_WIDTH, WINDOW_HEIGHT);
	glutInitWindowPosition(100, 100);

	glutInitDisplayMode( GLUT_SINGLE | GLUT_RGB );

	glutCreateWindow("Falling Particle !");
	glutDisplayFunc(Mostrar);

	glutTimerFunc(TIME,Animation,1);

	glutMainLoop();

	return 0;
}
